<template>
  <div id="box">
    <div class="fl" style="margin: 10px;width: 98%;">
      <div class="fl">
        <el-select v-model="queryType" placeholder="请选择">
          <el-option v-if="!(this.$store.getters.hospitalId == 76 || this.$store.getters.hospitalId == 201)" value="胸痛" />
          <el-option value="卒中" />
        </el-select>
      </div>
      <div class="fl" style="margin-left: 15px;">
        <el-button type="primary" @click="queryList();">查询</el-button>
      </div>
      <div class="fr">
        <el-button type="primary" @click="clearAll();rapidDispensingChange=true">新增快速给药</el-button>
      </div>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column fixed prop="tempName" label="快速给药方案名称" align="center" />
      <el-table-column prop="content" label="快速给药方案描述" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.meidcineDetail" :key="index">
            {{ item.medicineName }}{{ item.medicineDosage }}{{ item.medicineUnit }}
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClick(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="delLine(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block textR">
      <el-pagination
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableTotal"
        :hide-on-single-page="!true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 增改模板 -->
    <el-dialog
      title="配置快速给药"
      :visible.sync="rapidDispensingChange"
      class="dialogStyle"
      width="60%"
      top="15px"
      :close-on-click-modal="false"
    >
      <p>
        <el-radio-group v-model="medicineType" @change="changeClear()">
          <el-radio-button label="胸痛" />
          <el-radio-button label="卒中" />
        </el-radio-group>
      </p>

      <el-button-group v-if="medicineType=='胸痛' ">
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = chestPain.dapt">抗血小板药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = chestPain.aceiorarb">ACEI/ARB</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = chestPain.anticoagulant">抗凝药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = chestPain.statins">他汀类</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = chestPain.retardant">β受体阻滞剂</el-button>
      </el-button-group>
      <el-button-group v-if="medicineType=='卒中' ">
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.dapt">抗血小板药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.anticoagulant">抗凝药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.bloodPressureDown">降压药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.antidiabetic">降糖药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.lipid">调脂药</el-button>
        <el-button type="success" round @click="innerVisible = true; modelData.drugTemplate = apoplexy.antivasospasm">抗血管痉挛药</el-button>
      </el-button-group>
      <div class="box-card" shadow="hover" style="margin-top: 15px;">
        <el-form label-position="right" label-width="100px">
          <el-form-item label="方案名称">
            <el-input v-model.trim="modelData.tempName" style="width: 80%;" />
          </el-form-item>
          <div style="border: #eee solid 1px; padding: 10px 15px 10px 0; min-height: 100px;">
            <div v-for="(item,index) in saveList" :key="index">
              <el-row :gutter="20" style="padding: 10px;    line-height: 40px;">
                <el-col :span="2">{{ index+1 }}</el-col>
                <el-col :span="4"> {{ item.medicineType }}</el-col>
                <el-col :span="8"> {{ item.medicineName }}</el-col>
                <el-col :span="4">
                  <el-input v-model.trim="item.medicineDosage" />
                </el-col>
                <el-col :span="4">
                  <el-select v-model="item.medicineUnit " placeholder="请选择">
                    <el-option value="mg" />
                    <el-option value="ml" />
                    <el-option value="IU" />
                    <el-option value="片" />
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <el-button type="danger" plain @click="delDrugIndex(index,item.medicineName )">删除</el-button>
                </el-col>
              </el-row>
            </div>
          </div>

        </el-form>
      </div>

      <el-dialog width="60%" title="选择药物" :visible.sync="innerVisible" append-to-body style="text-align: center;">
        <el-checkbox-group v-model="modelData.checkList">
          <el-checkbox
            v-for="(items,$index) in modelData.drugTemplate"
            :key="$index"
            :label="items"
            border
            style="margin-bottom: 10px;"
            @change="addDelList(items,$index)"
          />
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
          <el-button type="success" @click="innerVisible = false">确 定</el-button>
        </span>
      </el-dialog>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rapidDispensingChange = false">取 消</el-button>
        <el-button type="primary" @click="saveData()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script type="text/javascript">
import {
  queryList,
  delMedicine,
  saveMedicine
} from '@/api/back-management/rapid_dispensing.js'
export default {
  name: '',
  data() {
    return {
      tableData: [], // 页面表格数据源
      currentPage: 1,
      tableTotal: 0,
      pageNum: 1, // 当前页
      pageSize: 10, // 每页的数量
      rapidDispensingChange: false,
      innerVisible: false,
      medicineType: '胸痛',
      modelData: { // dialog数据
        id: '',
        tempName: '',
        checkList: [], // 小弹出选中的多选-存值
        drugTemplate: [] // 小弹出可选的多选值
      },
      queryType: (this.$store.getters.hospitalId == '76' || this.$store.getters.hospitalId == 201) ? '卒中' : '胸痛',
      saveList: [], // 弹出页面下方
      chestPain: {
        /* 抗血小板药*/
        dapt: ['阿司匹林', '氯吡格雷', '替格瑞洛', '普拉格雷', '西洛他唑'],
        /* ACEI/ARB*/
        aceiorarb: ['贝那普利', '依那普利', '赖诺普利', '卡托普利', '福辛普利', '摩西普利', '培哚普利', '雷米普利', '缬沙坦', '氯沙坦', '厄贝沙坦', '坎地沙坦',
          '替米沙坦',
          '奥美沙坦', '单片复方制剂', '沙库巴曲缬沙坦钠'
        ],
        /* 他汀类（调脂药物）*/
        statins: ['阿托伐他汀', '瑞舒伐他汀', '洛伐他汀', '普伐他汀', '辛伐他汀', '氟伐他汀', '匹伐他汀', '依洛尤单抗', '依折麦布', '阿利西尤单抗'], // 他汀类（调脂药物）
        /* 抗凝药*/
        anticoagulant: ['普通肝素', '低分子肝素', '比伐卢定', '黄达肝葵钠', '依诺肝素钠'],
        /* β受体阻滞剂*/
        retardant: ['酒石酸美托洛尔', '琥珀酸美托洛尔', '比索洛尔', '阿替洛尔', '普萘洛尔', '奈必洛尔', '卡维地洛']
      },
      apoplexy: {
        /* 抗血小板药*/
        dapt: ['阿司匹林', '替格瑞洛', '氯吡格雷', '替罗非班', '阿西单抗', '普拉格雷', '依替巴肽', '西洛他唑', '奥扎格雷', '双嘧达莫', '塞氯吡啶'],
        /* 抗凝药*/
        anticoagulant: ['普通肝素', '双香豆素', '依诺肝素', '替他肝素', '阿地肝素', '华法林', '硝酸香豆素', '枸橼酸钠', '磺达肝癸钠', '比伐卢定', '利伐沙班',
          '达比加群', '阿哌沙班', '依度沙班', '低分子肝素'
        ],
        /* 降压药*/
        bloodPressureDown: ['ACEI', 'ARB', '利尿剂', 'β受体阻滞剂', '钙拮抗剂'],
        /* 降糖药 */
        antidiabetic: ['胰岛素', '磺酰脲类', '双胍类', 'α糖苷酶抑制剂', '胰岛素增敏剂', '非磺酰脲类促胰岛素分泌剂'],
        /* 调脂药 */
        lipid: ['他汀类', '烟酸及其衍生物', '贝特类', '胆固醇吸收抑制剂'],
        /* 抗血管痉挛药 */
        antivasospasm: ['尼莫地平', '法舒地尔']
      }
    }
  },
  mounted() {
    this.queryList() // 进入页面默认查询
    console.log('快速给药')
  },
  methods: {
    saveData() {
      if (this.modelData.tempName === '') {
        this.$message({
          message: '方案名称不能为空',
          type: 'warning'
        })
        return false
      }

      for (const el in this.saveList) {
        if (this.saveList[el].medicineDosage === '') {
          const emptyCheck = this.saveList[el].medicineName
          this.$message({
            message: `药物 ${emptyCheck} 剂量不能为空`,
            type: 'warning'
          })
          return false
        }
      }

      const data = {
        userId: this.$store.getters.userId,
        hospitalId: this.$store.getters.hospitalId,
        tempName: this.modelData.tempName,
        detail: JSON.stringify(this.saveList),
        greentype: this.medicineType
      }
      let type = ''
      if (this.modelData.id) {
        data.id = this.modelData.id
        type = '修改'
      } else {
        type = '保存'
      }

      saveMedicine(data).then(res => {
        if (res.code === 9999) {
          this.$message({
            type: 'error',
            message: type + '失败!'
          })
        } else {
          this.$message({
            type: 'success',
            message: type + '成功!'
          })
          this.queryList()
          this.rapidDispensingChange = false
          this.clearAll()
        }
      })
    },
    changeClear() { // 切换类别时清空之前的数据
      this.saveList = []
      this.modelData.checkList = []
      this.modelData.drugTemplate = []
    },
    clearAll() { // 清除全部值
      this.modelData.id = ''
      this.modelData.tempName = ''
      this.modelData.checkList = []
      this.modelData.drugTemplate = []
      this.saveList = []
      this.medicineType = '胸痛'
    },
    addDelList(medicine) { // 根据点击多选增减下方药物列表
      /* 发生change事件运行至此,已完成对数组checkList的增减, 在此相应对saveList做出增减*/
      const arrIndex = this.modelData.checkList.indexOf(medicine)
      if (arrIndex === -1) { // 若不存在,说明该药物被取消选中
        this.delDrugName(medicine) // 根据药名删除药品
      } else { // 若存在,说明该药物被选中
        this.addDrugName(medicine) // 故根据药名向saveList添加药品
      }
    },
    addDrugName(name) { // 根据药名向saveList添加药品
      let type = ''
      if (this.medicineType === '胸痛') {
        type = this.chestPain.dapt.indexOf(name) > -1 ? '抗血小板药' : type
        type = this.chestPain.aceiorarb.indexOf(name) > -1 ? 'ACEI/ARB' : type
        type = this.chestPain.statins.indexOf(name) > -1 ? '他汀类' : type
        type = this.chestPain.anticoagulant.indexOf(name) > -1 ? '抗凝药' : type
        type = this.chestPain.retardant.indexOf(name) > -1 ? 'β受体阻滞剂' : type
      } else {
        type = this.apoplexy.dapt.indexOf(name) > -1 ? '抗血小板药' : type
        type = this.apoplexy.anticoagulant.indexOf(name) > -1 ? '抗凝药' : type
        type = this.apoplexy.bloodPressureDown.indexOf(name) > -1 ? '降压药' : type
        type = this.apoplexy.antidiabetic.indexOf(name) > -1 ? '降糖药' : type
        type = this.apoplexy.lipid.indexOf(name) > -1 ? '调脂药' : type
        type = this.apoplexy.antivasospasm.indexOf(name) > -1 ? '抗血管痉挛药' : type
      }
      this.saveList.push({
        medicineType: type,
        medicineName: name,
        medicineDosage: '',
        medicineUnit: 'mg'
      })
    },
    delDrugName(name) { // 根据药名删除药品
      let arrIndex = ''
      this.saveList.forEach((el, index) => {
        if (el.medicineName === name) {
          arrIndex = index
          return
        }
      })
      if (arrIndex !== '') { /* 注意这里 ( 0!="") ->false      */
        this.saveList.splice(arrIndex, 1)
      }
    },

    delDrugIndex(index, drueName) { // 药品删除按钮(根据索引)
      this.saveList.splice(index, 1)
      const arrIndex = this.modelData.checkList.indexOf(drueName)
      this.modelData.checkList.splice(arrIndex, 1)
    },

    handleClick(row) { // 回显-将表格值显示到弹出的dialog中
      this.clearAll()
      this.modelData.tempName = row.tempName
      this.saveList = this.filterMeidcineDetail(row.meidcineDetail)
      this.modelData.id = row.id
      this.modelData.checkList = this.filterCheckBox(row.meidcineDetail)
      this.rapidDispensingChange = true
      this.medicineType = row.greentype || '胸痛'
      console.log(row)
    },
    // modelData.checkList
    filterCheckBox(arr) { // 过滤返回值,将返回的药物数据, 格式化为页面checkList(药品多选)需要的格式
      const arrs = []
      arr.forEach((el) => {
        arrs.push(el.medicineName)
      })
      return arrs
    },
    filterMeidcineDetail(arr) { // 过滤返回值,将返回的药物数据, 格式化为页面saveList需要的格式
      const arrs = []
      arr.forEach((el) => {
        arrs.push({
          medicineType: el.medicineType,
          medicineName: el.medicineName,
          medicineDosage: el.medicineDosage,
          medicineUnit: el.medicineUnit
        })
      })
      return arrs
    },
    // resetList(){
    // 	this.pageNum= 1;
    // 	this.pageNum= 10
    // }
    // 查询页面表格
    queryList() {
      const data = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        greentype: this.queryType,
        apiToken: this.$store.getters.apiToken
        // 'apiToken': sessionStorage.getItem("APITOKEN"),
      }
      queryList(data).then(res => {
        this.tableData = res.data.list
        this.tableTotal = res.data.total
      })
    },
    delLine(id) { // 删除一条给药方案
      this.$confirm('此操作将永久删除该方案, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delMedicine({
          'ids': id
        }).then(res => {
          if (res.code === 9999) {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.queryList()
          }
        })
      })
      // .catch(() => {
      // this.$message({
      //   type: 'info',
      //   message: '已取消删除'
      // });
      // });
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.queryList()
      console.log(`当前页: ${val}`)
    }
  }
}
</script>
<style scoped>
  .dialogStyle {
    text-align: center;
    min-width: 700px;
    /* min-height: 400px; */
  }
</style>
